package top.wilsonlv.jaguar.cloud.gateway.swagger;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger.web.SwaggerResource;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

import static java.util.Optional.of;

/**
 * @author lvws
 * @since 2022/3/17 0017
 */
@Primary
@Component
public class SwaggerProvider implements SwaggerResourcesProvider {


    public static final String API_URI = "/v2/api-docs";

    /**
     * 网关应用名称
     */
    @Value("${spring.application.name}")
    private String applicationName;

    @Resource
    private RouteLocator routeLocator;


    @Override
    public List<SwaggerResource> get() {
        //服务名称列表
        List<String> routeHosts = new ArrayList<>();
        // 获取所有可用的应用名称
        routeLocator.getRoutes()
                .filter(route -> route.getUri().getHost() != null && !applicationName.equals(route.getUri().getHost()))
                .subscribe(route -> routeHosts.add(route.getUri().getHost()));

        //接口资源列表
        List<SwaggerResource> resources = new ArrayList<>();
        for (String host : routeHosts) {
            // 拼接url
            String url = "/" + host + API_URI;
            SwaggerResource swaggerResource = new SwaggerResource();
            swaggerResource.setName(host);
            swaggerResource.setUrl(swaggerLocation(url, host));
            resources.add(swaggerResource);
        }
        return resources;
    }

    private String swaggerLocation(String swaggerUrl, String swaggerGroup) {
        String base = of(swaggerUrl).get();
        if (Docket.DEFAULT_GROUP_NAME.equals(swaggerGroup)) {
            return base;
        }
        return base + "?group=" + swaggerGroup;
    }
}
